package com.zxmr.webclient.listener;

import java.util.Calendar;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.zxmr.CommonInit;
import com.zxmr.action.QueueWithoutExchangeReceiver;
import com.zxmr.asyn.AsynRequestRegister;
import com.zxmr.asyn.TaskMonitor;
import com.zxmr.audit.Audit;
import com.zxmr.audit.AuditScheduleCallBack;
import com.zxmr.component.SystemConstant;
import com.zxmr.util.Utils;
import com.zxmr.webclient.ComponentInit;
import com.zxmr.webclient.Constant;
import com.zxmr.webclient.audit.ResourceAudit;
import com.zxmr.webclient.component.ComponentsRepository;
import com.zxmr.webclient.upload.UploaderFactory;

public class InitListener implements ServletContextListener {

	TaskMonitor monitor = new TaskMonitor(1,1);
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		initBaseDir(arg0);
		initDB();
		initComponentsRepository();
		initAsynMonitor();
		System.out.println("start response queue");
		initResponseQueue();
		UploaderFactory.init();
		initAudit();
	}
	private void initResponseQueue()
	{
		try
		{
			ExecutorService es = Executors.newCachedThreadPool();
			QueueWithoutExchangeReceiver response = new QueueWithoutExchangeReceiver(es,Constant.sourceQueue);

			es.execute(response);
			

		}catch (Exception e) {
			e.printStackTrace();
		}

		
	}
	private void initDB()
	{
		String url = InitListener.class.getClassLoader().getResource("").getPath();
		CommonInit.initCommonSqlMapper(url+"/mybatis-config.xml");
		ComponentInit.initCommonSqlMapper(url+"/component-db-config.xml");
	}
	private void initComponentsRepository()
	{
		ComponentsRepository.init();
	}
	private void initAsynMonitor()
	{
		
		AsynRequestRegister.setMonitor(monitor);
		Thread thread = new Thread(monitor);
		thread.start();
	}
	
	private void initAudit()
	{
		Audit deleteFile = new ResourceAudit(monitor);
		AuditScheduleCallBack callback = new AuditScheduleCallBack(deleteFile);
		
		Calendar cal = Calendar.getInstance(); 
		cal.set(Calendar.HOUR_OF_DAY, 24); 
		cal.set(Calendar.SECOND, 0); 
		cal.set(Calendar.MINUTE, 0); 
		cal.set(Calendar.MILLISECOND, 0); 

		long time = Utils.timeFromNow(cal.getTime());
		System.out.println("audit will start after "+time+" ms");
		monitor.addTask(callback, time);
	}

	private void initBaseDir(ServletContextEvent arg0)
	{
		String url = InitListener.class.getClassLoader().getResource("").getPath();
		System.out.println("base dir is "+url);
		SystemConstant.setBasedir(url);
	}
	
}
